package xyz.jiang.common.utils;

import io.jsonwebtoken.CompressionCodecs;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import io.jsonwebtoken.security.Keys;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;
import xyz.jiang.common.mapper.UsersMapper;

import javax.crypto.SecretKey;
import java.util.Date;
import java.util.List;

import static xyz.jiang.common.constants.TokenConstants.TOKEN_EXPIRE_TIME;

@Component
public class TokenUtils {


    private static UsersMapper usersMapper;

    @Autowired
    public void setUsersMapper(UsersMapper usersMapper) {
        TokenUtils.usersMapper = usersMapper;
    }

    public static String crateToken(String username) {

        SecretKey key = Keys.secretKeyFor(SignatureAlgorithm.HS512);
        return Jwts.builder()
                .subject(username)
                .expiration(new Date(System.currentTimeMillis() + TOKEN_EXPIRE_TIME * 1000))
                .signWith(key)
                .compressWith(CompressionCodecs.GZIP)
                .compact();
    }

    public static String getToken(ServerHttpRequest request) {
        List<String> tokens = request.getHeaders().get("token");
        if (CollectionUtils.isEmpty(tokens)) {
            return null;
        }
        return tokens.get(0);
    }
}
